<template>
  <div class="wrapper">
    <!-- PDF 渲染容器 -->
    <PdfPreview ref="pdfPreviewRef">
      <SignatureOverlay
        v-for="(sig, index) in signatureAreas"
        :key="index"
        :signerInfo.sync="sig"
        mode="viewStatus"
      />
    </PdfPreview>
    <view style="display: flex; justify-content:center; padding: 40px;">
      <u-button v-if="showSignBtn" type="primary" text="開始簽呈" style="width: 40%;" @click="handleSubmit"></u-button>
    </view>
  </div>
</template>

<script>
import PdfPreview from "@/pages/petition/common/components/PdfPreview.vue";
import SignatureOverlay from "@/pages/petition/common/components/SignatureOverlay.vue";
import SignatureInputDialog from "@/pages/petition/common/components/SignatureInputDialog.vue";
import SignatureDate from "@/pages/petition/common/typeComs/SignatureDate.vue";
export default {
  components: {
    PdfPreview,
    SignatureOverlay,
    SignatureInputDialog,
    SignatureDate,
  },
  props: {
    infoData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      previewData: {},
      activeSignInfo: {},
      activeIndex: -1,
      signatureAreas: [],
      showSignBtn: false,
    };
  },
  watch: {
    infoData: {
      handler(val) {
        if (Object.keys(val).length) {
          const { previewData, petitionInfo } = val;
          this.previewData = previewData;
          this.$nextTick(async () => {
            try {
              uni.showLoading({ mask: true });
              await this.$refs.pdfPreviewRef.loadDataFromServer(
                previewData.templateBasicId
              );
              this.signatureAreas = previewData.boxList.map((item) => {
                // 是否显示开始签字按钮 通过返回盒子的禁用属性 只要有一个不是禁用 就显示
                const user = item.userList?.[0] || {};
                let fieldValue;
                if (item.boxType === 1 || item.boxType === 5) {
                  fieldValue = user.templateSignatureOssUrl;
                } else {
                  fieldValue = user.signatureContent;
                }
                return { ...item, fieldValue };
              });
              // 先过滤掉自己能签字的 再判断签字区域中是否存在未完成签署的用户（遍历每个区域下的所有用户）
              this.isHaveNotSign = this.signatureAreas.some(area =>
                // 遍历该区域下所有用户，只要有一个签署状态不是 5，就返回 true
                !area.signatureState
              )
              this.showSignBtn = petitionInfo.petitionState === 1 && this.isHaveNotSign
              uni.hideLoading();
            } catch (error) {
              uni.hideLoading();
            }
          });
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
  },
  methods: {
    handleSubmit() {
      uni.redirectTo({url: '/pages/petition/signContract/index?id='+ this.$route.query.id})
    },
  },
};
</script>

<style scoped>
.wrapper {
  padding: 20rpx;
}
</style>
